//
//  ChaKanBiXingShouCangTianKongTiViewController.swift
//  CKC
//
//  Created by 张振东 on 2016/10/22.
//  Copyright © 2016年 ZZD. All rights reserved.
//

import UIKit
import RealmSwift

class ChaKanBiXingShouCangTianKongTiViewController: UIViewController {

    let screenWidth = UIScreen.main.bounds.width
    let screenHeight = UIScreen.main.bounds.height
    var navigationHeight:CGFloat?
    
    //定义一个iamgeView,存储随机生成的图片
    var topImageView:UIImageView?
    
    //定义一个变量:记录题号的值,默认为1
    var tiHao:Int = 1
    
    //定义几个label对象,保存题干内容
    var tiHaoLabel:UILabel?
    var tiGanNeiRongLabel:UILabel?
    var hengXianLabel:UILabel?
    var userInputNumberLabel:UILabel?
    
    //定义一个按钮:下一题
    var nextQuestionBtn:UIButton?

    //保存从数据库中查询出来的结果集
    var biXingTianKongTiItems:Results<BiXingTianKongTi>?
    
    //定义一个变量,存储收藏的题目的个数
    var biXingTianKongTiItemsCount:Int = 0
    
    //定义一个变量,初始化为0
    var index:Int = 0
    
    
    //定义一个变量,用于保存随机生成的图片的名称
    var topImageName:String?
    
    var topImage:UIImage?
    
    //定义一个变量,保存生成的图片的笔形吗
    var topImageViewBiXingCode:Int = 0
    
    override func viewDidLoad() {
        
        //使用默认的数据库
        let realm = try! Realm()
        //查询所有的消费记录
        biXingTianKongTiItems = realm.objects(BiXingTianKongTi.self)
        
        print(biXingTianKongTiItems as Any)
        biXingTianKongTiItemsCount = (biXingTianKongTiItems?.count)!
        
        self.title = "我的收藏"
        self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white,NSFontAttributeName:UIFont(name: "STHeitiSC-Medium", size: 20.0)!]
        
        self.view.backgroundColor = UIColor(red: 246,green: 246,blue: 246,alpha: 1)
        let leftBarButton = UIButton(frame:CGRect(x: 0,y: 0,width: 20,height: 20))
        leftBarButton.setBackgroundImage(UIImage(named: "fanhui"), for: UIControlState())
        leftBarButton.addTarget(self, action: #selector(backToPrevious), for: .touchUpInside)
        let leftBarButtonItem = UIBarButtonItem(customView: leftBarButton)
        self.navigationItem.leftBarButtonItems = [leftBarButtonItem]
        
        //设置右边的按钮
        let rightBarButton = UIButton(frame:CGRect(x: screenWidth-20,y: 0,width: 20,height: 20))
        rightBarButton.setBackgroundImage(UIImage(named: "qingkongshoucang"), for: UIControlState())
        let rightBarButtonItem = UIBarButtonItem(customView: rightBarButton)
        rightBarButton.addTarget(self, action: #selector(qingKongShouCang), for: .touchUpInside)
        
        self.navigationItem.rightBarButtonItems = [rightBarButtonItem]

        
        fengZhuangKongJianShuXing()
        

        // Do any additional setup after loading the view.
    }

    
    /*
     作者:张振东
     日期:2017-10-23
     功能:封装lable属性
     */
    func fengZhuangLabelAttributes(_ label:UILabel){
        label.font = UIFont(name: "FontAwesome",size: 15)
        switch label {
        case tiHaoLabel!:
            label.text = "\(tiHao)"
            label.font = UIFont(name: "FontAwesome",size: 20)
            break
        case tiGanNeiRongLabel!:
            label.text = "、以下笔形对应的笔形码为"
            break
        case hengXianLabel!:
            label.text = "_______."
            break
        case userInputNumberLabel!:
            label.text = ""
            label.textAlignment = .center
            label.font = UIFont(name: "FontAwesome",size: 18)
            break
        default:
            print("封装完毕")
        }
    }

    /*
     作者:张振东
     日期:2017-10-20
     功能:封装button属性
     */
    func fengZhuangButtonAttributes(_ button:UIButton){
        button.setTitleColor(UIColor.black, for: UIControlState())
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        button.backgroundColor = UIColor(red: 231/255,green: 76/255,blue: 60/255,alpha: 1)
        button.layer.cornerRadius = 20
        switch button {
        case nextQuestionBtn!:
            button.setTitle("下一个", for: UIControlState())
            break
            
        default:
            print("封装button")
        }
    }

    
    func fengZhuangKongJianShuXing(){
        //获取导航栏的高度
        navigationHeight = self.navigationController?.navigationBar.bounds.size.height
        
        //初始化iamgeView
        topImageView = UIImageView(frame:CGRect(x:50,y:navigationHeight!+30,width:screenWidth-100,height:screenWidth-100))
        topImageView!.contentMode = .scaleAspectFit
        
        //初始化题干label对象
        tiHaoLabel = UILabel(frame:CGRect(x: 10,y: navigationHeight!+screenWidth-60,width: 20,height: 30))
        fengZhuangLabelAttributes(tiHaoLabel!)
        
        //初始化题干内容label对象
        tiGanNeiRongLabel = UILabel(frame:CGRect(x: 20,y: navigationHeight!+screenWidth-60,width: 210,height: 30))
        fengZhuangLabelAttributes(tiGanNeiRongLabel!)
        
        hengXianLabel = UILabel(frame:CGRect(x: 20+210,y: navigationHeight!+screenWidth-60,width: 60,height: 30))
        fengZhuangLabelAttributes(hengXianLabel!)
        
        userInputNumberLabel = UILabel(frame:CGRect(x: 20+210,y: navigationHeight!+screenWidth-60,width: 60,height: 30))
        fengZhuangLabelAttributes(userInputNumberLabel!)
        
        nextQuestionBtn = UIButton(frame:CGRect(x: 10,y: screenHeight-50,width: screenWidth-20,height: 40))
        //初始化下一题按钮
        fengZhuangButtonAttributes(nextQuestionBtn!)
        
        if biXingTianKongTiItemsCount == 0{
            fengZhuangYaoXianShiDeKongJianWeiLingShi()
        }else{
            fengZhuangYaoXianShiDeKongJian()
            self.tiHaoLabel?.text = biXingTianKongTiItems![index].tiHao
            self.userInputNumberLabel?.text = biXingTianKongTiItems![index].userInputNumber
            topImageName = biXingTianKongTiItems![index].topImageName
            topImage = UIImage(named: topImageName!)
            topImageView?.image = topImage
            topImageViewBiXingCode = Int(((topImageName! as NSString)).substring(with: NSMakeRange(0, 1)))!
            if topImageViewBiXingCode == Int(biXingTianKongTiItems![index].userInputNumber!)!{
                self.userInputNumberLabel?.textColor = UIColor.green
            }else{
                self.userInputNumberLabel?.textColor = UIColor.gray
            }
            //点击下一题进行更新传递过来的7个字符串
            nextQuestionBtn?.addTarget(self, action: #selector(clickNextQuestion), for: .touchUpInside)
        }

    }
    
    /*
     作者:张振东
     日期:2017-10-22
     功能:当收藏的个数=0时,所有控件不需要显示
     */
    func fengZhuangYaoXianShiDeKongJianWeiLingShi(){
        
    }
    
    /*
     作者:张振东
     日期:2017-10-22
     功能:当收藏的个数>0时,添加所有控件
     */
    func fengZhuangYaoXianShiDeKongJian(){
        self.view.addSubview(topImageView!)
        self.view.addSubview(tiHaoLabel!)
        self.view.addSubview(tiGanNeiRongLabel!)
        self.view.addSubview(hengXianLabel!)
        self.view.addSubview(userInputNumberLabel!)
        self.view.addSubview(nextQuestionBtn!)
        super.viewDidLoad()
    }
    
    /*
     作者:张振东
     日期:2016-10-23
     功能:清空当前页面的收藏
     */
    func qingKongShouCang(){
        print(index)
        qingChuDangQianShouCangTi(index)
    }
    
    /*
     作者:张振东
     日期:2016-10-23
     功能:清空当前页面的收藏
     */
    func qingChuDangQianShouCangTi(_ index:Int){
        if index < biXingTianKongTiItemsCount{
            //使用默认的数据库
            let realm = try! Realm()
            try! realm.write{
                realm.delete(biXingTianKongTiItems![index])
            }
            //biXingTianKongTiItemsCount要跟着发生变化,数量减1
            biXingTianKongTiItemsCount = biXingTianKongTiItemsCount - 1
            //弹出一个提示框,显示没有收藏题了
            let alertController = UIAlertController(title: "温馨提示",message: "亲,清除成功!",preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            let okAction = UIAlertAction(title: "好的", style: .default, handler: {
                action in
                print("点击了确定")
            })
            alertController.addAction(cancelAction)
            alertController.addAction(okAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
    
    /*
     作者:张振东
     日期:2017-10-23
     功能:点击下一个收藏的时候,重新生成新的图片
     */
    func clickNextQuestion(){
        index = index + 1
        print(index)
        if index < biXingTianKongTiItemsCount{
            gengXinShouCangTi(index)
        }else{
            index = biXingTianKongTiItemsCount - 1
        }
        
    }
    
    
    /*
     作者:张振东
     日期:2017-10-23
     功能:该方法实现根据不同的index,显示不同的收藏题
     */
    func gengXinShouCangTi(_ index:Int){
        if index < biXingTianKongTiItemsCount{
            self.tiHaoLabel?.text = biXingTianKongTiItems![index].tiHao
            self.userInputNumberLabel?.text = biXingTianKongTiItems![index].userInputNumber
            topImageName = biXingTianKongTiItems![index].topImageName
            topImage = UIImage(named: topImageName!)
            topImageView?.image = topImage
            topImageViewBiXingCode = Int(((topImageName! as NSString)).substring(with: NSMakeRange(0, 1)))!
            if topImageViewBiXingCode == Int(biXingTianKongTiItems![index].userInputNumber!)!{
                self.userInputNumberLabel?.textColor = UIColor.green
            }else{
                self.userInputNumberLabel?.textColor = UIColor.gray
            }
        }else{
            //弹出一个提示框,显示没有收藏题了
            let alertController = UIAlertController(title: "温馨提示",message: "亲,没有下一题了",preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            let okAction = UIAlertAction(title: "好的", style: .default, handler: {
                action in
                print("点击了确定")
            })
            alertController.addAction(cancelAction)
            alertController.addAction(okAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
    
    func backToPrevious(){
        self.navigationController?.popViewController(animated: true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
